import { cloneDeep } from 'lodash-es'
interface TreeHelperConfig {
  id: string
  children: string
  parentId: string
}

const DEFAULT_CONFIG: TreeHelperConfig = {
  id: 'id',
  children: 'children',
  parentId: 'parentId'
}
export const defaultProps = {
  children: 'children',
  label: 'name',
  value: 'id',
  isLeaf: 'leaf',
  emitPath: false // 用于 cascader 组件：在选中节点改变时，是否返回由该节点所在的各级菜单的值所组成的数组，若设置 false，则只返回该节点的值
}

/**
 * 获取树结构数据的默认配置
 * @param config
 * @returns
 */
const getConfig = (config: Partial<TreeHelperConfig>) => Object.assign({}, DEFAULT_CONFIG, config)

// tree from list
export const listToTree = <T = any>(list: any[], config: Partial<TreeHelperConfig> = {}): T[] => {
  const conf = getConfig(config) as TreeHelperConfig
  const nodeMap = new Map()
  const result: T[] = []
  const { id, children, parentId } = conf

  for (const node of list) {
    node[children] = node[children] || []
    nodeMap.set(node[id], node)
  }
  for (const node of list) {
    const parent = nodeMap.get(node[parentId])
    ;(parent ? parent.children : result).push(node)
  }
  return result
}

export const treeToList = <T = any>(tree: any, config: Partial<TreeHelperConfig> = {}): T => {
  config = getConfig(config)
  const { children } = config
  const result: any = [...tree]
  for (let i = 0; i < result.length; i++) {
    if (!result[i][children!]) continue
    result.splice(i + 1, 0, ...result[i][children!])
  }
  return result
}

export const findNodeById = (tree: any, v: number | string, config: Partial<TreeHelperConfig> = {}) => {
  config = getConfig(config)
  const { id } = config
  for (const node of tree) {
    if (node[id!] === v) {
      const nodeData = cloneDeep(node)
      nodeData.children = []
      return node
    }
    if (node.children && node.children.length > 0) {
      const findChild = findNodeById(node.children, v, config)
      if (findChild) return findChild
    }
  }
  return null
}

export const filter = <T = any>(tree: T[], func: (n: T) => boolean, config: Partial<TreeHelperConfig> = {}): T[] => {
  config = getConfig(config)
  const children = config.children as string

  function listFilter(list: T[]) {
    return list
      .map((node: any) => ({ ...node }))
      .filter(node => {
        node[children] = node[children] && listFilter(node[children])
        return func(node) || (node[children] && node[children].length)
      })
  }

  return listFilter(tree)
}

export const forEach = <T = any>(tree: T[], func: (n: T) => any, config: Partial<TreeHelperConfig> = {}): void => {
  config = getConfig(config)
  const list: any[] = [...tree]
  const { children } = config
  for (let i = 0; i < list.length; i++) {
    // func 返回true就终止遍历，避免大量节点场景下无意义循环，引起浏览器卡顿
    if (func(list[i])) {
      return
    }
    children && list[i][children] && list.splice(i + 1, 0, ...list[i][children])
  }
}

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
export const handleTree = (data: any[], id?: string, parentId?: string, children?: string) => {
  if (!Array.isArray(data)) {
    console.warn('data must be an array')
    return []
  }
  const config = {
    id: id || 'id',
    parentId: parentId || 'parentId',
    childrenList: children || 'children'
  }

  const childrenListMap = {}
  const nodeIds = {}
  const tree: any[] = []

  for (const d of data) {
    const parentId = d[config.parentId]
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = []
    }
    nodeIds[d[config.id]] = d
    childrenListMap[parentId].push(d)
  }

  for (const d of data) {
    const parentId = d[config.parentId]
    if (nodeIds[parentId] == null) {
      tree.push(d)
    }
  }

  for (const t of tree) {
    adaptToChildrenList(t)
  }

  function adaptToChildrenList(o) {
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]]
    }
    if (o[config.childrenList]) {
      for (const c of o[config.childrenList]) {
        adaptToChildrenList(c)
      }
    }
  }

  return tree
}

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 * @param {*} rootId 根Id 默认 0
 */
// @ts-ignore
export const handleTree2 = (data, id, parentId, children, rootId) => {
  id = id || 'id'
  parentId = parentId || 'parentId'
  // children = children || 'children'
  rootId =
    rootId ||
    Math.min(
      ...data.map(item => {
        return item[parentId]
      })
    ) ||
    0
  // 对源数据深度克隆
  const cloneData = JSON.parse(JSON.stringify(data))
  // 循环所有项
  const treeData = cloneData.filter(father => {
    const branchArr = cloneData.filter(child => {
      // 返回每一项的子级数组
      return father[id] === child[parentId]
    })
    branchArr.length > 0 ? (father.children = branchArr) : ''
    // 返回第一层
    return father[parentId] === rootId
  })
  return treeData !== '' ? treeData : data
}

/**
 * 校验选中的节点，是否为指定 level
 *
 * @param tree 要操作的树结构数据
 * @param nodeId 需要判断在什么层级的数据
 * @param level 检查的级别, 默认检查到二级
 * @return true 是；false 否
 */
export const checkSelectedNode = (tree: any[], nodeId: any, level = 2): boolean => {
  if (typeof tree === 'undefined' || !Array.isArray(tree) || tree.length === 0) {
    console.warn('tree must be an array')
    return false
  }

  // 校验是否是一级节点
  if (tree.some(item => item.id === nodeId)) {
    return false
  }

  // 递归计数
  let count = 1

  // 深层次校验
  function performAThoroughValidation(arr: any[]): boolean {
    count += 1
    for (const item of arr) {
      if (item.id === nodeId) {
        return true
      } else if (typeof item.children !== 'undefined' && item.children.length !== 0) {
        if (performAThoroughValidation(item.children)) {
          return true
        }
      }
    }
    return false
  }

  for (const item of tree) {
    count = 1
    if (performAThoroughValidation(item.children)) {
      // 找到后对比是否是期望的层级
      if (count >= level) {
        return true
      }
    }
  }

  return false
}

/**
 * 获取节点的完整结构
 * @param tree 树数据
 * @param nodeId 节点 id
 */
export const treeToString = (tree: any[], nodeId) => {
  if (typeof tree === 'undefined' || !Array.isArray(tree) || tree.length === 0) {
    console.warn('tree must be an array')
    return ''
  }
  // 校验是否是一级节点
  const node = tree.find(item => item.id === nodeId)
  if (typeof node !== 'undefined') {
    return node.name
  }
  let str = ''

  function performAThoroughValidation(arr) {
    for (const item of arr) {
      if (item.id === nodeId) {
        str += ` / ${item.name}`
        return true
      } else if (typeof item.children !== 'undefined' && item.children.length !== 0) {
        str += ` / ${item.name}`
        if (performAThoroughValidation(item.children)) {
          return true
        }
      }
    }
    return false
  }

  for (const item of tree) {
    str = `${item.name}`
    if (performAThoroughValidation(item.children)) {
      break
    }
  }
  return str
}

/**
 * 树结构数据添加level字段及添加辅助线相关逻辑字段
 * @param treeData 树形结构数据
 * @param isLast 是否是当前层级最后一条数据
 * @param hideLine 哪些层级的线可以隐藏
 * @param level 当前层级
 */
export const treeLevel = (treeData, isLast, hideLine, level) => {
  treeData.forEach((item, index) => {
    item.level = level + 1
    if (index === 0) {
      item.isFirst = true
    } else {
      item.isFirst = false
    }
    if (index === treeData.length - 1) {
      item.isLast = true
    } else {
      item.isLast = false
    }
    item.hideLine = cloneDeep(hideLine)
    if (isLast) {
      item.hideLine.push(item.level - 1)
    }
    item.isLeaf = true
    if (item.children && item.children.length > 0) {
      item.isLeaf = false
      treeLevel(item.children, item.isLast, item.hideLine, item.level)
    }
  })
}

// 格式化树结构的关键key、value
export const treeFormat = <T = any>(data, key, value, func: (n: T) => boolean) => {
  data.forEach((item: any) => {
    item.label = item[key]
    item.value = item[value]
    item.disabled = func(item)
    if (item.children && item.children.length > 0) {
      treeFormat(item.children, key, value, func)
    }
  })
}

const ascending = (arr: any) => {
  return arr.sort((a: any, b: any) => {
    return a?.sort - b?.sort
  })
}

// 树形结构数据递归排序
export const treeToAscending = (arr: any) => {
  const newTree = ascending(arr)
  newTree.forEach(function (item: any) {
    if (item.children && item.children.length > 0) {
      item.children = treeToAscending(item.children)
    }
  })
  return newTree
}

// 通过当前选中节点找其所有祖先层级
export const getTreeNodeParents = (list, node, config: Partial<TreeHelperConfig> = {}) => {
  let arrRes: any = []
  const rev = (data, v, config) => {
    config = getConfig(config)
    const { id, parentId } = config
    for (let i = 0; i < data.length; i++) {
      const item = data[i]
      if (item[id] === v[parentId]) {
        const itemData = cloneDeep(item)
        itemData.children = []
        arrRes.unshift(itemData)
        rev(list, item, config)
        break
      } else {
        if (item.children && item.children.length > 0) {
          rev(item.children, v, config)
        }
      }
    }
    return arrRes
  }
  arrRes = rev(list, node, config)
  return arrRes
}
// 通过当前选中节点找其所有子层级
export const getTreeNodeChildren = (list, node, config: Partial<TreeHelperConfig> = {}) => {
  let arrRes: any = []
  const rev = (data, v, config) => {
    config = getConfig(config)
    const { id } = config
    for (let i = 0; i < data.length; i++) {
      const item = data[i]
      if (item[id] === v[id]) {
        const itemData = cloneDeep(item)
        arrRes.unshift(itemData)
        break
      } else {
        if (item.children && item.children.length > 0) {
          rev(item.children, v, config)
        }
      }
    }
    return arrRes
  }
  arrRes = rev(list, node, config)
  const res = treeToList(arrRes)
  return res
}

// 获取 id 集合
export const getIdFromArray = (data, config: Partial<TreeHelperConfig> = {}) => {
  const res: number[] = []
  config = getConfig(config)
  const { id } = config
  data.forEach(item => {
    res.push(item[id!])
  })
  return res
}
